#
# Copyright 2009 Jeffrey Palm
#
require 'config'
require 'util'
require 'server'
require 'key_finder'
require 'has_a_shared_key'

# This type of KeyFinder waits for someone to send them the key.  This
# is why it has the HasASharedKey interface, too.
class WaitsForKey < KeyFinder

  attr_reader   :config
  attr_accessor :shared_key

  def initialize(config)
    @config = config
  end

  def find_the_shared_key
    note 'Begin waiting for the shared key'
    note 'IP Address = ' + private_ip_address  
    s = Server.new SharedKeyHandler.new(self)
    s.start '127.0.0.1',config.port
    note 'Done waiting for the shared key'
    note 'Shared key: ' + @shared_key
    return @shared_key
  end  

  # Instances of this class are responsible for recieving requests on
  # a socket that contain the shared key, storing it, and then giving
  # it to the enclosing instance
  class SharedKeyHandler < Server::Handler

    # Pass in the enclosing instance of Resumep3
    def initialize(has_a_shared_key)
      super 'Tortilla Bob'
      @has_a_shared_key = has_a_shared_key
    end

    # Here, we:
    #
    #   1. Take the shared key from the request.
    #   2. Write it out to disk for later.
    #   3. Give it to the enclosing instance.
    #
    # If anything goes wrong we return 'false'.  But if we're able to
    # get a shared key, store it, and give it up, we return 'true'.
    #
    def handle(request)

      # We'll assume now that the entire request is the key
      begin
        note 'Setting the shared key to ' + request
        @has_a_shared_key.shared_key = request
      rescue Exception => e

        # For an exception we need to keep listening probably to get
        # another shared key
        return error e
      end

      # If we've gotten this far, we don't want to listen for the key
      # any more, so return 'true', meaning we're done
      true
    end
  end

end
